package cn.syc.struck.demo.fragment;

import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.widget.TextView;

import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.orhanobut.logger.Logger;

import java.util.ArrayList;
import java.util.List;

import cn.syc.struck.demo.R;
import cn.syc.struck.demo.adapter.AppAdapter;
import cn.syc.struck.demo.base.BaseFragment;
import cn.syc.struck.demo.bean.AppInfo;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * Created by chenzz on 2017/3/23.
 */

public class AppsFragment extends BaseFragment {
    public static final String CLASS_TAG = "AppsFragment";

    private XRecyclerView mRecyclerView;
    private AppAdapter mAdapter;
    private List<AppInfo> listData;
    private View mEmptyView;

    private TextView textView_text;

    //当前页码

    @Override
    protected int getLayoutId() {
        return R.layout.activity_recyclerview;
    }

    @Override
    protected void afterCreate(Bundle savedInstanceState) {

        mRecyclerView = (XRecyclerView) mRootView.findViewById(R.id.recyclerview);
        textView_text = (TextView) mRootView.findViewById(R.id.textView_text);
        LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mRecyclerView.setLayoutManager(layoutManager);

        //----------add2-------
        mEmptyView = mRootView.findViewById(R.id.include_view_empty);
        mRecyclerView.setEmptyView(mEmptyView);
        //-----------2---------

        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallSpinFadeLoader);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallRotate);
        mRecyclerView.setArrowImageView(R.drawable.iconfont_downgrey);

        //View header = LayoutInflater.from(getActivity()).inflate(R.layout.recyclerview_header, (ViewGroup) mRootView.findViewById(android.R.id.content), false);
        //mRecyclerView.addHeaderView(header);
        mRecyclerView.setLoadingMoreEnabled(false);
        //mRecyclerView.setPullRefreshEnabled(false);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //textView_text.setText("正在加载...");
                listData.clear();
                loadApp();
            }

            @Override
            public void onLoadMore() {
            }
        });

        listData = new ArrayList<AppInfo>();
        mAdapter = new AppAdapter(listData);

        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.refresh();

        //========================
        mRootView.findViewById(R.id.button_reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //相当于重新下拉刷新
                mRecyclerView.refresh();
                mRecyclerView.refreshComplete();
            }
        });
        //--------------------------
    }

    private void loadApp() {
        //首选我们需要调用系统api来获取所有已安装的app，所以在OnSubscribe的call方法中调用getApplicationInfoList()。
        // 但是getApplicationInfoList()获取的数据并不能完全满足我们的业务需求：

        //由于我们只需要展示手机上已安装的第三方App，因此需要通过filter操作符来过滤掉系统app；
        //ApplicationInfo并不是我们所需要的类型，因此需要通过map操作符将其转换为AppInfo；
        //由于获取ApplicationInfo、过滤数据、转换数据相对比较耗时，因此需要通过subscribeOn操作符将这一系列操作放到子线程中来处理；
        //而要将信息展示在页面上涉及到UI操作，因此需要通过observeOn操作符将onNext、onCompleted、onError调度到主线程，接着我们在这些方法中更新UI。
        final PackageManager pm = getActivity().getPackageManager();
        Observable.create(new Observable.OnSubscribe<ApplicationInfo>() {
            @Override
            public void call(Subscriber<? super ApplicationInfo> subscriber) {
                List<ApplicationInfo> infoList = getApplicationInfoList(pm);
                Logger.d("total=" + infoList.size());
                for (ApplicationInfo info : infoList) {
                    subscriber.onNext(info);
                }
                subscriber.onCompleted();
            }
        }).filter(new Func1<ApplicationInfo, Boolean>() {
            @Override
            public Boolean call(ApplicationInfo applicationInfo) {
                //展示手机上已安装的第三方App，因此需要通过filter操作符来过滤掉系统app
                return (applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) <= 0;
            }
        }).map(new Func1<ApplicationInfo, AppInfo>() {

            @Override
            public AppInfo call(ApplicationInfo applicationInfo) {
                AppInfo info = new AppInfo();
                info.setAppIcon(applicationInfo.loadIcon(pm));
                info.setAppName(applicationInfo.loadLabel(pm).toString());
                Logger.d("name=" + info.getAppName());
                return info;
            }
        }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<AppInfo>() {
                    @Override
                    public void onCompleted() {
                        mAdapter.notifyDataSetChanged();
                        mRecyclerView.refreshComplete();

                    }

                    @Override
                    public void onError(Throwable e) {
                        mRecyclerView.refreshComplete();
                        textView_text.setText(e.getMessage());
                    }

                    @Override
                    public void onNext(AppInfo appInfo) {
                        //mAppInfoList.add(appInfo);
                        listData.add(appInfo);
                    }
                });
    }

    private List<ApplicationInfo> getApplicationInfoList(final PackageManager pm) {
        return pm.getInstalledApplications(PackageManager.GET_UNINSTALLED_PACKAGES);
    }

}
